var carousel = document.querySelector("ul"),
	carousel_box = document.querySelector(".carousel_box");
	left_arrow = document.querySelector(".left_arrow"),
	right_arrow = document.querySelector(".right_arrow"),
	controls = document.querySelectorAll("ol li"),
	now_index = 0,last_index = 0,
	is_run = false,
	timer = null;
//右箭头点击事件
right_arrow.addEventListener("click", function() {
	if(!is_run){
		is_run = true;
		++now_index >= 5 ? now_index = 0 : "";
		run(now_index);
	}
})
//左箭头点击事件
left_arrow.addEventListener("click", function() {
	if(!is_run){
		is_run = true;
		--now_index < 0 ? now_index = 4 : "";
		run(now_index);
	}
})
//圆点控制-自定义属性
//for(var i = 0;i<controls.length;i++){
//	controls[i].setAttribute("data-index",i);
//	controls[i].addEventListener("mouseover",function(){
//		run(this.getAttribute("data-index"));
//	})
//}
//圆点控制-事件代理
//controls[0].parentNode.addEventListener("mouseover",function(e){
//	for(var i = 0;i<controls.length;i++){
//		if(e.target == controls[i]){
//			run(i);
//		}
//	}
//})
//圆点控制-闭包
for(var i = 0;i<controls.length;i++){
	(function(z){
		controls[z].addEventListener("mouseover",function(){
		now_index = z;
		run(z);
		})
	})(i)
}

autoplay();

//鼠标移入停止轮播图
carousel_box.addEventListener("mouseover",function(){
	clearInterval(timer);
})
//鼠标移开运行轮播图
carousel_box.addEventListener("mouseout",function(){
	autoplay();
})
//轮播图运行主函数
function run(target_index){
	carousel.style.transform = "translateX(-" + target_index * 100 + "%)";
	controls[last_index].classList.remove("active");
	last_index = target_index;
	controls[target_index].classList.add("active");
	carousel.addEventListener("transitionend",function(){
		is_run = false;
	})
}
//自动轮播
function autoplay(){
	timer = setInterval(function(){
		++now_index >= 5 ? now_index = 0 : "";
		run(now_index);
	},2000)
}
